<template>
  <view class="header-container">
    <view :style="getGridStyle" class="header-grid">
      <view v-for="(header, index) in gridCell" :key="index" class="header-item"
            :style="getCellStyle(header,header.colIndex)">
        <view class="header-item-label">{{ header.label }}</view>
      </view>
    </view>

  </view>
</template>

<script>
/**
	 * 表头组件
   * 目前最多只支持二级表头
	 * @author shiliu
	 *
	 * @props {columns} 表头数据列表 
	 *
	 * @tips 示例数据：columns: [
          {
            label: '分类',
            children: [],
            prop: 'type',
            width:'40%',
          },
          {
            label: '总实收营业额（元）',
            width:'30%',
            children: [
              { label: '数值（占比）', prop: 'totalPercent', slot: 'customSlot',width:'100%', },
            ]
          },
          {
            label: '总毛利额（元）',
            width:'30%',
            children: [
              { label: '数值（占比）', prop: 'name',width:'100%' },
            ]
          },
        ],
   * 
	 */
export default {
  name: 'DataTableHeader',
  props: {
    columns: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {}
  },
  computed: {
    getGridStyle() {
      const columnWidths = this.flattenColumnList.map(col => col.width || '1fr').join(' ')
      return {
        display: 'grid',
        gridTemplateColumns: columnWidths,
        width: '100%'
      }
    },
    gridCell() {
      let maxLevel = 1
      this.columns.map(item => {
        if (item.children?.length) {
          maxLevel = 2
        }
      })
      let cells = Array(maxLevel).fill().map(() => [])
      const loopCell = (arr, level) => {
        arr.map((item, index) => {
          cells[level].push({
            ...item,
            rowspan: 1,
            colspan: 1,
            display: true
          })
          if (item.children?.length) {
            if (item.children.length > 1) {
              let extraCells = Array(item.children.length - 1).fill(0)
              cells[level] = cells[level].concat(extraCells)
            }
            if (cells[level + 1].length < index + 1) {
              let extraCells = Array(index - cells[level + 1].length).fill(0);
              cells[level + 1] = cells[level + 1].concat(extraCells)
            }
            loopCell(item.children, level + 1)
          }
        })
      }
      loopCell(this.columns, 0)
      let _cells = JSON.parse(JSON.stringify(cells))
      const loopColumns = (columns, level,startIndex) => {
        columns.map((item, index) => {
          let _index=startIndex+index
          if (!item.children?.length&&!level&&item.label) {
            _cells[level][_index] = {
              ...item,
              rowspan: maxLevel,
              colspan: 1,
              display: true,
              rowIndex: level,
              colIndex: _index,
            }
            for (let i = 1; i < maxLevel; i++) {
              if (level + i < maxLevel) {
                _cells[level + i][_index] = {
                  ..._cells[level + i][_index],
                  display: false,
                  rowIndex: level,
                  colIndex: _index,
                }
              }
            }
          } else if (item.children?.length >= 1) {
            _cells[level][_index] = {
              ...item,
              rowspan: 1,
              colspan: item.children.length,
              display: true,
              rowIndex: level,
              colIndex: _index,
            }
            for (let i = 1; i < item.children.length; i++) {
              _cells[level][_index + i] = {
                ..._cells[level][_index + i],
                display: false,
                rowIndex: level,
                colIndex: _index+i,
              }
            }
            loopColumns(item.children, level + 1,index)
          } else {
            if(_cells[level][_index].display){
              _cells[level][_index] = {
                ...item,
                rowspan: 1,
                colspan: 1,
                display: true,
                rowIndex: level,
                colIndex: _index,
              }
            }
          }
        })
      }
      loopColumns(_cells[0], 0,0)
      return _cells.flat().filter(cell => cell.display)
    },
    flattenColumnList() {
      const result = []
      const flatten = (cols, parent) => {
        cols.forEach(col => {
          if (col.children && col.children.length) {
            flatten(col.children, col)
          } else {
            if (parent?.width && col?.width) {
              let pWidth=Number(parent.width.split('%')[0])*0.01
              let cWidth=Number(col.width.split('%')[0])*0.01
              result.push({
                ...col,
                width:pWidth*cWidth*100+'%'
              })
            } else {
              result.push(col)
            }
            // result.push(col)
          }
        })
      }
      flatten(this.columns,null)
      return result
    }
  },
  methods: {
    // 计算每个label的高度
    getCellStyle(cell, colIndex) {
      const baseWidth = this.flattenColumnList[colIndex].width
      let width = baseWidth

      // 处理列合并的宽度
      if (cell.colspan > 1) {
        const colWidths = []
        for (let i = 0; i < cell.colspan; i++) {
          colWidths.push(this.flattenColumnList[colIndex + i].width || '100px')
        }
        width = colWidths.reduce((sum, w) => {
          const numWidth = parseInt(w)
          return sum + (isNaN(numWidth) ? 100 : numWidth)
        }, 0) + 'px'
      }

      return {
        //   width: width,
        flex: baseWidth ? 'none' : '1',
        display: cell.display ? 'flex' : 'none',
        color: cell.textColor || '#333',
        fontWeight: cell.bold ? 'bold' : 'normal',
        gridRow: `span ${cell.rowspan}`,
        gridColumn: `span ${cell.colspan}`
      }
    },
  }
}
</script>

<style lang="scss">
.header-container {
  display: flex;
  width: 100%;
  background-color: #F5F6FA;
  // border-top: 1px solid #E7EAF2;
  border-left: 1px solid #E7EAF2;

  .header-grid {
    display: grid;
  }

  .header-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-right: 1px solid #E7EAF2;
    border-top: 1px solid #E7EAF2;
    box-sizing: border-box;

    .header-item-label {
      // display: flex;
      // align-items: center;
      // justify-content: center;
      padding: 8px 4px;
      font-size: 10px;
      color: #1A1A1A;
      text-align: center;
      word-break: break-all;
      box-sizing: border-box;

      &+.header-item-label {
        border-top: 1px solid #E7EAF2;
      }
    }

    .flex {
      display: flex;
      border-top: 1px solid #E7EAF2; // 添加边框以确保对齐
    }

    .flex .header-item-label {
      flex: 1;

      &+.header-item-label {
        border-left: 1px solid #E7EAF2;
      }
    }
  }
}
</style>
